package com.gmcloud.test.jasypt.controller;

import com.gmcloud.common.utils.JsonUtil;
import com.gmcloud.common.utils.R;
import com.gmcloud.test.jasypt.common.Const;
import com.gmcloud.test.jasypt.dto.JasyptDto;
import com.ulisesbocchio.jasyptspringboot.encryptor.DefaultLazyEncryptor;
import org.jasypt.encryption.StringEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/9/6 19:54
 */
@RestController
@RequestMapping({"/", "jasypt"})
public class JasyptController {


    private final static String JASYPT_ENCRYPTOR_PASSWORD = "jasypt.encryptor.password";

    private final static Logger LOGGER = LoggerFactory.getLogger(JasyptController.class);

    @GetMapping
    public ModelAndView jasypt(ModelAndView modelAndView, @RequestParam(required = false) String error) {
        modelAndView.setViewName("ftl/jasypt");
        modelAndView.addObject("error", error);
        return modelAndView;
    }

    @PostMapping("encrypted")
    public R encrypted(@RequestBody JasyptDto jasyptDto) {
        LOGGER.info(JsonUtil.objToString(jasyptDto));

        System.setProperty(JASYPT_ENCRYPTOR_PASSWORD, jasyptDto.getKey());
        StringEncryptor stringEncryptor = new DefaultLazyEncryptor(new StandardEnvironment());

//        switch (jasyptDto.getTab()) {
//            case "config":
                if (Const.encrypt.equals(jasyptDto.getType())) {
                    //加密方法
                    return R.ok(stringEncryptor.encrypt(jasyptDto.getOriginal()));

                }//解密方法
                if (Const.decrypt.equals(jasyptDto.getType())) {
                    return R.ok(stringEncryptor.decrypt(jasyptDto.getOriginal()));
                }
//                break;
//            case "basic":
//
//                break;
//            case "password":
//
//                break;
//            default:
//                LOGGER.info("不支持此操作");
//        }
        return R.failed("加/解密失败");
    }
}
